﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WXYW.Entities;
using WXYW.DAL;
using WXYW.Model;
using System.Data.EntityClient;
using System.Data;
namespace WXYW.BLL
{
    public class ApplicationService : RepositoryBase
    {
        public long AddApplication(long userID, int providerID, string applicationType, string status)
        {
            ApplicationForm applicationForm = new ApplicationForm();
            //rmaApplicationForm.ApplicationID = applicationID;
            applicationForm.ApplicationDateTime = DateTime.Now;
            applicationForm.ApplicationType = applicationType;
            applicationForm.IsSubmit = false;
            applicationForm.Status = status;

            UserService userService = new UserService();
            applicationForm.User = userService.GetUserByID(userID);

            ProviderService providerService = new ProviderService();
            //applicationForm.Provider = providerService.GetProviderByID(providerID);

            InsertEntity(applicationForm);

            return applicationForm.ApplicationID;
        }

        public long AddApplication(ApplicationForm form)
        {
            InsertEntity(form);
            return form.ApplicationID;
        }

        public ApplicationForm ConfirmRMACode(long applicationID, int serviceStationID)
        {
            ServiceStation serviceStation = GetServiceStationByID(serviceStationID);
            ApplicationForm application = GetEntities<ApplicationForm>(p => p.ApplicationID == applicationID).FirstOrDefault();
            if (application.ApplicationType.Equals("R"))
            {
                application.ApplicationCode = RunningNumberService.GenerateRMANumber(serviceStation.ForShort);
            }
            else if (application.ApplicationType.Equals("D"))
            {
                application.ApplicationCode = RunningNumberService.GenerateDOMNumber(serviceStation.ForShort);
            }
            else if (application.ApplicationType.Equals("C"))
            {
                application.ApplicationCode = RunningNumberService.GenerateSRNumber(serviceStation.ForShort);
            }
            application.Status = "收货待确认";
            application.ServiceStation = serviceStation;
            application.RMANOGenerateDateTime = DateTime.Now;
            UpdateEntity(application);
            if (!application.UserReference.IsLoaded)
            {
                application.UserReference.Load();
            }
            return application;
        }

        public ApplicationForm GetApplicationByRunningNO(string runningNO)
        {
            return GetEntities<ApplicationForm>().Where(a => a.RunningNumber.Equals(runningNO)).FirstOrDefault();
        }

        public ApplicationForm ConfirmReceivedProduct(long applicationID)
        {
            ApplicationForm application = GetEntities<ApplicationForm>(p => p.ApplicationID == applicationID).FirstOrDefault();
            application.Status = "待派单";
            application.ReceiveDateTime = DateTime.Now;
            UpdateEntity(application);
            return application;
        }

        public string FinishDistributeForm(long applicationID)
        {
            ApplicationForm application = GetEntities<ApplicationForm>(p => p.ApplicationID == applicationID).FirstOrDefault();
            application.Status = "待修";
            application.DistributeDateTime = DateTime.Now;
            UpdateEntity(application);
            return application.ApplicationCode;
        }

        public void AddEmptyApplicationProduct(long applicationID)
        {
            ApplicationProduct applicationProduct = new ApplicationProduct();
            applicationProduct.ApplicationForm = GetApplicationFormByID(applicationID);
            applicationProduct.ProductCount = 1;
            InsertEntity(applicationProduct);
        }

        public IQueryable<ApplicationProduct> GetApplicationProductsByApplicationID(long applicationID)
        {
            return GetEntities<ApplicationProduct>(p => p.ApplicationForm.ApplicationID == applicationID);
        }

        public ApplicationFormHistory GetOriginalApplicationFormByID(long originalApplicationID)
        {
            return GetEntities<ApplicationFormHistory>(p => p.ApplicationID == originalApplicationID).FirstOrDefault();
        }

        public ApplicationForm GetApplicationFormByID(long applicationID)
        {
            ApplicationForm applicationForm = GetEntities<ApplicationForm>(p => p.ApplicationID == applicationID).FirstOrDefault();            
            return applicationForm;
        }

        public ApplicationForm GetApplicationFormByRMACode(string code)
        {
            return GetEntities<ApplicationForm>(p => p.ApplicationCode == code).FirstOrDefault();
        }

        public ApplicationForm GetApplicationFormDetailByID(long applicationID)
        {
            ApplicationForm application = GetApplicationFormByID(applicationID);
            if (!application.UserReference.IsLoaded)
            {
                application.UserReference.Load();
            }
            if (!application.ApplicationProduct.IsLoaded)
            {
                application.ApplicationProduct.Load();
            }
            if (!application.ServiceStationReference.IsLoaded)
            {
                application.ServiceStationReference.Load();
            }

            foreach (ApplicationProduct product in application.ApplicationProduct)
            {
                if (!product.ProductTypeReference.IsLoaded)
                {
                    product.ProductTypeReference.Load();
                }
                if (!product.ProblemTypeReference.IsLoaded)
                {
                    product.ProblemTypeReference.Load();
                }
                if (!product.QuatationForm.IsLoaded)
                {
                    product.QuatationForm.Load();
                }
                if (!product.UserReference.IsLoaded)
                {
                    product.UserReference.Load();
                }

                if (product.QuatationForm.Count > 0)
                {
                    product.Cost = 0;
                    product.RepairAccessory = "";
                    product.ReasonOfCost = "";
                    foreach (QuatationForm quaForm in product.QuatationForm)
                    {
                        product.RepairAccessory += "," + quaForm.AccessoryName;
                        product.Cost += quaForm.Cost;
                        product.ReasonOfCost += "," + quaForm.Reason;
                    }

                    if (!string.IsNullOrEmpty(product.ReasonOfCost))
                    {
                        product.ReasonOfCost = product.ReasonOfCost.Substring(1);
                    }
                    if (!string.IsNullOrEmpty(product.RepairAccessory))
                    {
                        product.RepairAccessory = product.RepairAccessory.Substring(1);
                    }
                }
            }

            return application;

        }

        public List<ApplicationFormHistory> GetAllOriginalApplication(string keyword)
        {
            IQueryable<ApplicationFormHistory> formlist = GetEntities<ApplicationFormHistory>(a => (a.ApplicationType == "R" || a.ApplicationType == "D") && (!string.IsNullOrEmpty(a.RunningNumber))).OrderByDescending(p => p.ApplicationDateTime);
            if (!string.IsNullOrEmpty(keyword))
            {
                formlist = formlist.Where(a => a.ApplicationCode.Contains(keyword) || a.User.FullName.Contains(keyword));
            }
            foreach (ApplicationFormHistory form in formlist)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProductHistory.IsLoaded)
                {
                    form.ApplicationProductHistory.Load();
                }
            }

            return formlist.ToList();
        }

        public List<ApplicationFormHistory> GetAllOriginalApplicationPaging(string keyword, int pageIndex, int pageSize)
        {
            IQueryable<ApplicationFormHistory> formlist;
            if (!string.IsNullOrEmpty(keyword))
            {
                formlist = GetEntities<ApplicationFormHistory>(a => (a.ApplicationType == "R" || a.ApplicationType == "D") && (!string.IsNullOrEmpty(a.RunningNumber)));
                
                formlist = formlist.Where(a => a.ApplicationCode.Contains(keyword) || a.User.FullName.Contains(keyword));
                formlist = formlist.OrderByDescending(p => p.ApplicationDateTime).Skip(pageIndex * pageSize).Take(pageSize + 1);
            }
            else
            {
                formlist = GetEntities<ApplicationFormHistory>(a => (a.ApplicationType == "R" || a.ApplicationType == "D") && (!string.IsNullOrEmpty(a.RunningNumber))).
                OrderByDescending(p => p.ApplicationDateTime).Skip(pageIndex * pageSize).Take(pageSize + 1);
            }
            foreach (ApplicationFormHistory form in formlist)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProductHistory.IsLoaded)
                {
                    form.ApplicationProductHistory.Load();
                }
            }

            return formlist.ToList();
        }

        public int GetCountOfAllOriginalApplication(string keyword)
        {
            IQueryable<ApplicationFormHistory> formlist = GetEntities<ApplicationFormHistory>(a => (a.ApplicationType == "R" || a.ApplicationType == "D") && (!string.IsNullOrEmpty(a.RunningNumber))).
                OrderByDescending(p => p.ApplicationDateTime);
            if (!string.IsNullOrEmpty(keyword))
            {
                formlist = formlist.Where(a => a.ApplicationCode.Contains(keyword) || a.User.FullName.Contains(keyword));
            }
            return formlist.Count();
        }

        public ApplicationFormHistory GetOriginalApplicationDetailByID(long originalApplicationID)
        {
            ApplicationFormHistory application = GetOriginalApplicationFormByID(originalApplicationID);
            if (application != null)
            {
                if (!application.UserReference.IsLoaded)
                {
                    application.UserReference.Load();
                }
                //if (!application.ProviderReference.IsLoaded)
                //{
                //    application.ProviderReference.Load();
                //}
                if (!application.ApplicationProductHistory.IsLoaded)
                {
                    application.ApplicationProductHistory.Load();
                }
                foreach (ApplicationProductHistory product in application.ApplicationProductHistory)
                {
                    if (!product.ProductTypeReference.IsLoaded)
                    {
                        product.ProductTypeReference.Load();
                    }
                    if (!product.ProblemTypeReference.IsLoaded)
                    {
                        product.ProblemTypeReference.Load();
                    }
                }
            }
            return application;
        }

        public List<ApplicationForm> GetAllApplicationForm()
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>();
            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
            }

            return applicationForms.ToList();
        }

        public IQueryable<ApplicationForm> GetAllProcessingApplication(string keywrod)
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>().Where(a => !string.IsNullOrEmpty(a.RunningNumber) && a.IsSubmit == true).OrderByDescending(a => a.ApplicationDateTime);
            if (!string.IsNullOrEmpty(keywrod))
            {
                applicationForms = applicationForms.Where(a => a.ApplicationCode.Contains(keywrod)
                    || a.User.FullName.Contains(keywrod)
                    || a.User.ContactPerson.Contains(keywrod)
                    || a.User.CompanyName.Contains(keywrod)
                    || a.User.CompanyName.Contains(keywrod)
                    || a.ApplicationProduct.Where(p => p.ProductSerialNumber.Contains(keywrod)).Count() > 0
                    || a.ApplicationProduct.Where(p => p.ProductType.ProductTypeName.Contains(keywrod)).Count() > 0
                    || a.ApplicationProduct.Where(p => p.User.ContactPerson.Contains(keywrod)).Count() > 0);
            }

            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
            }
            return applicationForms;
        }

        public int GetTotalCountOfApplications(string keywrod)
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>().Where(a => !string.IsNullOrEmpty(a.RunningNumber) && a.IsSubmit == true).OrderByDescending(a => a.ApplicationDateTime);
            if (!string.IsNullOrEmpty(keywrod))
            {
                applicationForms = applicationForms.Where(a => a.ApplicationCode.Contains(keywrod)
                    || a.User.FullName.Contains(keywrod)
                    || a.User.ContactPerson.Contains(keywrod)
                    || a.User.CompanyName.Contains(keywrod)
                    || a.User.CompanyName.Contains(keywrod)
                    || a.ApplicationProduct.Where(p => p.ProductSerialNumber.Contains(keywrod)).Count() > 0
                    || a.ApplicationProduct.Where(p => p.ProductType.ProductTypeName.Contains(keywrod)).Count() > 0
                    || a.ApplicationProduct.Where(p => p.User.ContactPerson.Contains(keywrod)).Count() > 0);
            }
            return applicationForms.Count();
        }

        public IQueryable<ApplicationForm> GetAllProcessingApplicationPaging(string keywrod, int pageIndex, int pageSize)
        {
            IQueryable<ApplicationForm> applicationForms;
            if (!string.IsNullOrEmpty(keywrod))
            {
                applicationForms = GetEntities<ApplicationForm>().Where(a => !string.IsNullOrEmpty(a.RunningNumber) && a.IsSubmit == true).
                OrderByDescending(a => a.ApplicationDateTime);

                applicationForms = applicationForms.Where(a => a.ApplicationCode.Contains(keywrod)
                    || a.User.FullName.Contains(keywrod)
                    || a.User.ContactPerson.Contains(keywrod)
                    || a.User.CompanyName.Contains(keywrod)
                    || a.User.CompanyName.Contains(keywrod)
                    || a.ApplicationProduct.Where(p => p.ProductSerialNumber.Contains(keywrod)).Count() > 0
                    || a.ApplicationProduct.Where(p => p.ProductType.ProductTypeName.Contains(keywrod)).Count() > 0
                    || a.ApplicationProduct.Where(p => p.User.ContactPerson.Contains(keywrod)).Count() > 0);

                applicationForms = applicationForms.OrderByDescending(a => a.ApplicationDateTime).Skip(pageIndex * pageSize).
                Take(pageSize + 1);
            }
            else
            {
                applicationForms = GetEntities<ApplicationForm>().Where(a => !string.IsNullOrEmpty(a.RunningNumber) && a.IsSubmit == true).
                OrderByDescending(a => a.ApplicationDateTime).Skip(pageIndex*pageSize).
                Take(pageSize+1);
            }
            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
            }
            return applicationForms;
        }

        public List<ApplicationForm> GetApplicationFormsByUserID(long userID)
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>(p => p.User.UserID == userID && p.IsSubmit == true && !string.IsNullOrEmpty(p.RunningNumber)).OrderByDescending(a => a.ApplicationDateTime);
       
            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
                if (form.ApplicationProduct != null && !string.IsNullOrEmpty(form.ApplicationType) &&
                    form.ApplicationProduct.Count > 0 &&
                    (form.ApplicationType.Equals("BB") || form.ApplicationType.Equals("BD")))
                {
                    form.Status = form.ApplicationProduct.FirstOrDefault().Status;
                }
            }
          
                return applicationForms.ToList();
        }

        public int GetTotalCountOfApplicationsByUserID(long userID)
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>(p => p.User.UserID == userID && 
                p.IsSubmit == true && !string.IsNullOrEmpty(p.RunningNumber));
            return applicationForms.Count();
        }

        public List<ApplicationForm> GetApplicationsWaitForClientFeedBack()
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>(p => !string.IsNullOrEmpty(p.RunningNumber) && p.ApplicationProduct.Where(d => d.SendBackTime.HasValue).Count() > 0).OrderByDescending(a => a.SendBackDateTime);
            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
            }

            return applicationForms.ToList();
        }

        public List<ApplicationForm> GetApplicationNeedDistribute()
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>(p => p.IsSubmit == true && !string.IsNullOrEmpty(p.RunningNumber) && 
                !p.ApplicationType.StartsWith("B")&& !p.Status.Equals("等待RMA单号确认") && 
                !string.IsNullOrEmpty(p.ApplicationCode) && !p.Status.Equals("收货待确认") &&
                (p.ApplicationProduct.Where(pu => pu.DistributeDateTime == null || pu.Status.Equals("待派单")).Count() > 0)).OrderBy(p => p.ApplicationCode);
            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
            }

            return applicationForms.ToList();
        }

        public IQueryable<ApplicationForm> GetApplicationNeedConfirmApplicationCode()
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>(p => p.IsSubmit == true && (p.Status == "等待RMA单号确认") && !string.IsNullOrEmpty(p.RunningNumber) && !p.ApplicationType.StartsWith("B")).OrderByDescending(a => a.ApplicationDateTime);
            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
            }

            return applicationForms;
        }

        public List<ApplicationForm> GetRMAApplicationFormByStatus(string status)
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>(p => p.IsSubmit == true && p.Status == status && !string.IsNullOrEmpty(p.RunningNumber)).OrderByDescending(p => p.ApplicationDateTime);
            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
            }

            return applicationForms.ToList();
        }

        public List<ApplicationForm> GetRMAApplicationFormByStatus(string status, string keyword)
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>(p => p.IsSubmit == true && p.Status == status && !string.IsNullOrEmpty(p.RunningNumber)).OrderByDescending(p => p.ApplicationDateTime);
            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
            }

            List<ApplicationForm> applicationFormsList = applicationForms.ToList();

            if (!string.IsNullOrEmpty(keyword))
            {
                applicationFormsList = applicationForms.Where(p => p.ApplicationCode.Contains(keyword) || p.User.FullName.Contains(keyword) || p.User.ContactPerson.Contains(keyword) || p.User.UserPhone.Contains(keyword) || p.Status.Contains(keyword)).ToList();
            }
            return applicationFormsList.ToList();
        }

        public List<ApplicationForm> GetApplicationFormNeedGatering(string keyword)
        {
            //IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>(p => p.IsSubmit == true && 
            //    !string.IsNullOrEmpty(p.RunningNumber) && !p.SendBackDateTime.HasValue && p.QuatationDatetime.HasValue).OrderByDescending(p => p.ApplicationDateTime);
            //2012-08-07 Chen Pu
            //IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>(p => p.IsSubmit == true && 
            //    !string.IsNullOrEmpty(p.RunningNumber) &&　
            //    p.ApplicationProduct.Where(ap=>ap.ConfirmQuotationDateTime.HasValue && !ap.SendBackTime.HasValue).Count() > 0).OrderByDescending(p => p.ApplicationDateTime);
            //IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>().Where(a => a.ApplicationProduct.Where(p => p.QuatationForm.Where(q => !(q.IsBWBA.HasValue && q.IsBWBA.Value)).Count() > 0 &&
            //    (p.IsDecideToRepair.HasValue && p.IsDecideToRepair.Value)).Count() > 0 && a.Gathering == null && !a.SendBackDateTime.HasValue).OrderByDescending(a=>a.QuatationDatetime); // 2013.09.01
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && a.ConfirmQuatationCompleteDate.HasValue && 
                a.ApplicationProduct.Where(p => p.IsDecideToRepair.HasValue && p.IsDecideToRepair.Value && p.Cost > 0).Count() > 0 &&
                a.Status != "已发货待客户确认" && a.Status != "维修完毕待发货" && a.Status != "客户已收货确认" && a.Status != "客户信息反馈").OrderByDescending(a => a.ConfirmQuatationCompleteDate);
            List<ApplicationForm> formList = new List<ApplicationForm>();
            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
                if (!form.GatheringReference.IsLoaded)
                {
                    form.GatheringReference.Load();
                }
                if (form.Gathering == null)
                {
                    formList.Add(form);
                }
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                formList = formList.Where(p => p.ApplicationCode.Contains(keyword) || p.User.FullName.Contains(keyword) || p.User.ContactPerson.Contains(keyword) || p.User.UserPhone.Contains(keyword) || p.Status.Contains(keyword)).ToList();
            }
            return formList;
        }

        public List<ApplicationForm> GetApplicationsNeedConfirmReceive(int serviceStationID)
        {
            IQueryable<ApplicationForm> applicationForms = GetEntities<ApplicationForm>(p => p.IsSubmit == true && p.ServiceStation.ID == serviceStationID && p.Status == "收货待确认" && !string.IsNullOrEmpty(p.RunningNumber)).OrderByDescending(p => p.ApplicationDateTime);
            foreach (ApplicationForm form in applicationForms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
            }

            return applicationForms.ToList();
        }

        public List<ApplicationForm> GetApplicationNeedReceiptExpress(string keyword)
        {
            List<ApplicationForm> results = new List<ApplicationForm>();
            
            using (EntityConnection connection = new EntityConnection(DefaultEntitiesConnectionString))
            {
                WXYW.DAL.Entities ss = new WXYW.DAL.Entities(connection);
                results = ss.GetFormsNeedReceiptExpress().ToList();
                
                foreach (ApplicationForm form in results)
                {
                    if (!form.UserReference.IsLoaded)
                    {
                        form.UserReference.Load();
                    }
                    if (!form.ApplicationProduct.IsLoaded)
                    {
                        form.ApplicationProduct.Load();
                    }
                    if (!form.GatheringReference.IsLoaded)
                    {
                        form.GatheringReference.Load();
                    }
                }

                if (!string.IsNullOrEmpty(keyword))
                {
                    results = results.Where(s =>
                       (!string.IsNullOrEmpty(s.ApplicationCode) && s.ApplicationCode.Contains(keyword)) ||
                       (!string.IsNullOrEmpty(s.User.FullName) && s.User.FullName.Contains(keyword)) ||
                       (!string.IsNullOrEmpty(s.Gathering.RealPay.ToString()) && s.Gathering.RealPay.ToString().Contains(keyword))).ToList();
                }   
            }
            
            return results.OrderByDescending(a => a.Gathering.PayDateTime).ToList();
        }

        public int GetNumberOfApplication(string code)
        {
            return GetEntities<ApplicationForm>(p => p.RunningNumber.StartsWith(code)).Count();
        }

        public int GetNumberOfRMA(string code)
        {
            return GetEntities<ApplicationForm>(p => p.ApplicationCode.Contains(code)).Count();
        }

        public void PreviewApplication(long applicationID)
        {
            ApplicationForm application = GetEntities<ApplicationForm>(p => p.ApplicationID == applicationID).FirstOrDefault();
            if (application.RunningNumber == null)
            {
                application.RunningNumber = RunningNumberService.GenerateApplicationNumber();
            }
            UpdateEntity(application);
        }

        public void SubmitApplication(long applicationID)
        {
            ApplicationForm application = GetEntities<ApplicationForm>(p => p.ApplicationID == applicationID).FirstOrDefault();
            application.IsSubmit = true;
            UpdateEntity(application);
            InsertApplicationToApplicationHistory(application);
        }

        public bool AllProductFinishRepair(long applicationID)
        {
            List<ApplicationProduct> products = GetEntities<ApplicationProduct>().Where(a => a.ApplicationForm.ApplicationID == applicationID).ToList();
            if (products.Count(p => p.Status.Contains("完毕待发货")) == products.Count())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public List<ServiceStation> GetAllServiceStation()
        {
            return GetEntities<ServiceStation>().ToList();
        }

        public ServiceStation GetServiceStationByID(int serviceStationID)
        {
            return GetEntities<ServiceStation>(s => s.ID == serviceStationID).FirstOrDefault();
        }

        public List<ApplicationForm> GetApplicationFormByServiceStationAndStatus(int serviceStationID, string status)
        {
            //return GetEntities<ApplicationForm>(p => p.ServiceStation.ID == serviceStationID && p.Status.Equals(status)).ToList();
            List<ApplicationForm> forms = GetEntities<ApplicationForm>(p => p.ApplicationProduct.Where(ap => ap.Status.Equals(status)).Count() > 0).ToList();
            foreach (ApplicationForm form in forms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
            }

            return forms;
        }

        public void UpdateApplication(ApplicationForm form)
        {
            try
            {
                UpdateEntity(form);
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogMessgae("UpdateApplication::"+ex.ToString());
                throw ex;
            }
        }


        public List<ApplicationForm> GetApplicationsNeedSend(User currentUser, string keywords = "")
        {
            List<ApplicationForm> formslist = new List<ApplicationForm>();
            //冰川(1049776210)  21:51:35
            //到收款确认里面 是必须经过确认维修后才能流转到 收款确认和 待修里面 但是必须按照收款的作为最后的流程条件
            //很不想鼾睡(83588818)  21:51:39
            //只有bc都确认了才能到收费状太
            //冰川(1049776210)  21:51:54
            //en 
            //冰川(1049776210)  21:52:06
            //同时要到 待修里面 工程师要维修
            //冰川(1049776210)  21:53:00
            //如果工程师先维修完毕 那么不能到维修完毕待发货里面 必须等收款确认后才能流转到维修完毕待发货里面
            //IQueryable<ApplicationForm> results = GetEntities<ApplicationForm>(a => ((a.Status == "维修完毕待发货" || a.Status == "待修" || a.Status == "已付款待修") && !string.IsNullOrEmpty(a.RunningNumber) && !string.IsNullOrEmpty(a.ApplicationCode))
            //    && a.ApplicationProduct.Where(p => p.Status == "维修完毕待发货" && !p.SendBackTime.HasValue).Count() > 0 
            //    ||a.Status == "待付款确认" && a.ApplicationProduct.Where(p => p.Status == "维修完毕待发货" && p.IsDecideToRepair.HasValue && p.IsDecideToRepair == true).Count() > 0).OrderByDescending(a => a.ApplicationDateTime);
            //8.	平台管理员可以看到除北京以后所有平台维修完毕待发货的单子
            //10.	客服专员能够北京的所有待发货单子，包括升级的单子

            if (!currentUser.ServiceStationReference.IsLoaded)
            {
                currentUser.ServiceStationReference.Load();
            }
            if (!currentUser.UserTypeReference.IsLoaded)
            {
                currentUser.UserTypeReference.Load();
            }

            #region old code
            //List<ApplicationForm> results = GetEntities<ApplicationForm>(a => !string.IsNullOrEmpty(a.RunningNumber) && 
            //    !string.IsNullOrEmpty(a.ApplicationCode) && a.User != null &&
            //    (a.Status == "维修完毕待发货" || a.Status == "待修" ||
            //     a.Status == "报价确认中" || a.Status == "已付款待修" ||
            //     a.Status == "待付款确认")).ToList();
            //foreach (ApplicationForm form in results)
            //{
            //    if (!form.ApplicationProduct.IsLoaded)
            //    {
            //        form.ApplicationProduct.Load();
            //    }
            //    if (!form.GatheringReference.IsLoaded)
            //    {
            //        form.GatheringReference.Load();
            //    }
            //    if (!form.ServiceStationReference.IsLoaded)
            //    {
            //        form.ServiceStationReference.Load();
            //    }
            //    foreach (ApplicationProduct product in form.ApplicationProduct)
            //    {
            //        if (!product.UpgradeForm.IsLoaded)
            //        {
            //            product.UpgradeForm.Load();
            //        }
            //        if (!product.QuatationForm.IsLoaded)
            //        {
            //            product.QuatationForm.Load();
            //        }
            //        if (!product.UserReference.IsLoaded)
            //        {
            //            product.UserReference.Load();
            //        }
            //    }
            //}

            ////去除状态是付款确认，产品需要付费后再发货的表单
            //results = results.Where(a => a.Status != "待付款确认" || 
            //    a.ApplicationProduct.Where(p => p.SendBackTime.HasValue == false).Count() != 
            //    a.ApplicationProduct.Where(p => p.SendBackTime.HasValue == false && 
            //        p.IsDecideToRepair.HasValue==true && p.IsDecideToRepair.Value == true).Count()).ToList();

            //if ((currentUser.UserType.ID == (int)RoleType.Engineer || currentUser.UserType.ID == (int)RoleType.PlatformEngineer))
            //{
            //    results = results.Where(a => a.ServiceStation.ID == currentUser.ServiceStation.ID &&
            //               a.ApplicationProduct.Where(p =>
            //               p.Status == "维修完毕待发货" &&
            //                (p.UpgradeForm.Count == 0 ||
            //                (p.UpgradeForm.Count > 0 &&
            //                p.UpgradeForm.FirstOrDefault().Status == "升级-平台收货确认") ||
            //                //(p.UpgradeForm.Count > 0 &&
            //                // p.UpgradeForm.FirstOrDefault().SendWay == "客户" &&
            //                // p.UpgradeForm.FirstOrDefault().Status == "升级-完毕待发货") ||
            //                (p.UpgradeForm.Count > 0 &&
            //                 p.UpgradeForm.FirstOrDefault().Status == "升级-不同意")) &&
            //               (
            //               //p.ProductRepairType.Equals("保内") || 
            //               //(p.ProductRepairType.Equals("保外") && 
            //               (p.QuatationForm.Count() == 0 || 
            //               (p.QuatationForm.Count() > 0 && 
            //               (p.ApplicationForm.Gathering != null || p.IsDecideToRepair==false)))) &&
            //               !p.SendBackTime.HasValue).Count() > 0).ToList();
            //}
            //else if (currentUser.UserType.ID == (int)RoleType.PlatformAdmin)
            //{
            //    results = results.Where(a => 
            //        a.ApplicationProduct.Where(p => p.User.ServiceStation.ID != 1 &&
            //             p.Status == "维修完毕待发货" &&
            //                (p.UpgradeForm.Count == 0 ||
            //                (p.UpgradeForm.Count > 0 &&
            //                p.UpgradeForm.Where(u=>u.Status == "升级-平台收货确认").Count()>0 )||
            //                //(p.UpgradeForm.Count > 0 &&
            //                // p.UpgradeForm.FirstOrDefault().SendWay == "客户" &&
            //                // p.UpgradeForm.FirstOrDefault().Status == "升级-完毕待发货") ||
            //                (p.UpgradeForm.Count ==1 &&
            //                 p.UpgradeForm.FirstOrDefault().Status == "升级-不同意")) &&
            //               (
            //               //p.ProductRepairType.Equals("保内") ||
            //               //(p.ProductRepairType.Equals("保外") &&
            //               (p.QuatationForm.Count() == 0 ||
            //               (p.QuatationForm.Count() > 0 &&
            //               (p.ApplicationForm.Gathering != null || p.IsDecideToRepair == false)
            //               )
            //               )
            //               ) &&
            //               !p.SendBackTime.HasValue).Count() > 0).ToList();
            //}
            //else if (currentUser.UserType.ID == (int)RoleType.Service)
            //{
            //    results = results.Where(a => 
            //        a.ApplicationProduct.Where(p =>                         
            //             p.Status == "维修完毕待发货" &&
            //             (
            //                  (p.UpgradeForm.Count == 0 && (p.ApplicationForm.ApplicationCode.StartsWith("RBJ") || p.ApplicationForm.ApplicationCode.StartsWith("DBJ"))) ||
            //                  (p.UpgradeForm.Count > 0 && p.UpgradeForm.Where(u=>u.Status == "升级-平台收货确认").Count()>0) ||
            //                  (p.UpgradeForm.Count > 0 && p.UpgradeForm.Where(u=>u.SendWay == "客户" && u.Status == "升级完毕").Count()>0) ||
            //                  (p.UpgradeForm.Count ==1 && p.UpgradeForm.FirstOrDefault().Status == "升级-不同意")
            //              ) &&
            //              (    
            //                //p.ProductRepairType.Equals("保内") ||
            //                //  ( p.ProductRepairType.Equals("保外") &&
            //                    (  p.QuatationForm.Count() == 0 || 
            //                      (p.QuatationForm.Count() > 0 && (p.ApplicationForm.Gathering != null || p.IsDecideToRepair == false))
            //                     )
            //                   //)
            //               ) &&
            //               !p.SendBackTime.HasValue).Count() > 0).ToList();
            //}
            //else if (currentUser.ServiceStation != null &&
            //    (currentUser.UserType.ID != (int)RoleType.Administrator &&
            //    currentUser.UserType.ID != (int)RoleType.TBGLY &&
            //    currentUser.UserType.ID != (int)RoleType.QA))
            //{
            //    results = results.Where(a =>
            //        a.ApplicationProduct.Where(p =>
            //              p.Status == "维修完毕待发货" &&
            //                (p.UpgradeForm.Count == 0 ||
            //                (p.UpgradeForm.Count > 0 &&
            //                p.UpgradeForm.Where(u=>u.Status == "升级-平台收货确认").Count()>0) ||
            //                (p.UpgradeForm.Count > 0 &&
            //                 p.UpgradeForm.Where(u=>u.SendWay == "客户" &&
            //                 u.Status == "升级完毕").Count()>0 )||
            //                (p.UpgradeForm.Count == 1 &&
            //                 p.UpgradeForm.FirstOrDefault().Status == "升级-不同意")) &&
            //               (
                              
            //                   (     p.QuatationForm.Count() == 0 ||
            //                        ( p.QuatationForm.Count() > 0 &&
            //                          (p.ApplicationForm.Gathering != null || p.IsDecideToRepair == false)
            //                        )
            //                   )
            //               ) &&
            //               !p.SendBackTime.HasValue).Count() > 0).ToList();
            //}            
            //else
            //{
            //    results = results.Where(a => 
            //        a.ApplicationProduct.Where(p =>
            //           p.Status == "维修完毕待发货" &&
            //               (p.UpgradeForm.Count == 0 ||
            //                (p.UpgradeForm.Count > 0 &&
            //                p.UpgradeForm.Where(u=>u.Status == "升级-平台收货确认").Count()>0) ||
            //                (p.UpgradeForm.Count > 0 &&
            //                 p.UpgradeForm.Where(u=>u.SendWay == "客户" &&
            //                 u.Status == "升级完毕").Count()>0) ||
            //                (p.UpgradeForm.Count ==1 &&
            //                 p.UpgradeForm.FirstOrDefault().Status == "升级-不同意")) &&
            //                 (
            //                    //p.ProductRepairType.Equals("保内") ||
            //                    //( 
            //                    //  p.ProductRepairType.Equals("保外") &&
            //                      ( p.QuatationForm.Count() == 0 ||
            //                        ( p.QuatationForm.Count() > 0 &&
            //                          (p.ApplicationForm.Gathering != null || p.IsDecideToRepair == false)
            //                        )
            //                      )
            //                    //)
            //                 ) &&
            //               !p.SendBackTime.HasValue).Count() > 0).ToList();
            //}

            //foreach (ApplicationForm form in results)
            //{
            //    if (!form.UserReference.IsLoaded)
            //    {
            //        form.UserReference.Load();
            //    }
            //    if (!form.ApplicationProduct.IsLoaded)
            //    {
            //        form.ApplicationProduct.Load();
            //    }
            //    if (!form.CompleteDateTime.HasValue)
            //    {
            //        ApplicationProduct applicationProduct = form.ApplicationProduct.Where(p => p.Status == "维修完毕待发货").OrderBy(p => p.ApplicationProductID).FirstOrDefault();
            //        if (applicationProduct.RepairCompleteDateTime.HasValue)
            //        {
            //            form.CompleteDateTime = applicationProduct.RepairCompleteDateTime.Value;
            //        }
            //    }
            //    formslist.Add(form);
            //}
            #endregion
           
            if ((currentUser.UserType.ID == (int)RoleType.Engineer || currentUser.UserType.ID == (int)RoleType.PlatformEngineer))
            {
                formslist = GetEntities<ApplicationForm>().Where(a => a.ApplicationProduct.Where(p => p.RepairCompleteDateTime.HasValue && !p.SendBackTime.HasValue && p.User.ServiceStation.ID == currentUser.ServiceStation.ID &&
                (!(p.IsQuotePrice.HasValue && p.IsQuotePrice.Value) || !(p.IsDecideToRepair.HasValue && p.IsDecideToRepair.Value) || p.ApplicationForm.Gathering != null) &&
                (p.UpgradeForm.Count() == 0 || p.UpgradeForm.Where(u => u.Status == "升级-不同意").Count() > 0 || p.UpgradeForm.Where(u => u.SendWay == "客户" || (u.SendWay == "平台" && u.CompleteTime.HasValue)).Count() > 0)).Count() > 0).ToList();
            }
            else if (currentUser.UserType.ID == (int)RoleType.PlatformAdmin)
            {

               formslist = GetEntities<ApplicationForm>().Where(a => a.ApplicationProduct.Where(p => p.RepairCompleteDateTime.HasValue && !p.SendBackTime.HasValue && p.User.ServiceStation.ID != 1 &&
               (!(p.IsQuotePrice.HasValue && p.IsQuotePrice.Value) || !(p.IsDecideToRepair.HasValue && p.IsDecideToRepair.Value) || p.ApplicationForm.Gathering != null) &&
               (p.UpgradeForm.Count() == 0 || p.UpgradeForm.Where(u => u.Status == "升级-不同意").Count() > 0 || p.UpgradeForm.Where(u => u.SendWay == "客户" || (u.SendWay == "平台" && u.CompleteTime.HasValue)).Count() > 0)).Count() > 0).ToList();
            }
            else if (currentUser.UserType.ID == (int)RoleType.Service)
            {
                formslist = GetEntities<ApplicationForm>().Where(f => f.ApplicationCode.StartsWith("RBJ") || f.ApplicationCode.StartsWith("DBJ") && f.ApplicationProduct.Where(p => p.RepairCompleteDateTime.HasValue && !p.SendBackTime.HasValue &&
               (!(p.IsQuotePrice.HasValue && p.IsQuotePrice.Value) || !(p.IsDecideToRepair.HasValue && p.IsDecideToRepair.Value) || p.ApplicationForm.Gathering != null) &&
               (p.UpgradeForm.Count() == 0 || p.UpgradeForm.Where(u => u.Status == "升级-不同意").Count() > 0 || p.UpgradeForm.Where(u => u.SendWay == "客户" || (u.SendWay == "平台" && u.CompleteTime.HasValue)).Count() > 0)).Count() > 0).ToList();
            }
            else
            {
                formslist = GetEntities<ApplicationForm>().Where(a => a.ApplicationProduct.Where(p => p.RepairCompleteDateTime.HasValue && !p.SendBackTime.HasValue &&
               (!(p.IsQuotePrice.HasValue && p.IsQuotePrice.Value) || !(p.IsDecideToRepair.HasValue && p.IsDecideToRepair.Value) || p.ApplicationForm.Gathering != null) &&
               (p.UpgradeForm.Count() == 0 || p.UpgradeForm.Where(u => u.Status == "升级-不同意").Count() > 0 || p.UpgradeForm.Where(u => u.SendWay == "客户" || (u.SendWay == "平台" && u.CompleteTime.HasValue)).Count() > 0)).Count() > 0).ToList();
            }

            foreach (ApplicationForm applicationForm in formslist)
            {
                if (!applicationForm.UserReference.IsLoaded)
                {
                    applicationForm.UserReference.Load();
                }
                
                if (!applicationForm.User.ServiceStationReference.IsLoaded)
                {
                    applicationForm.User.ServiceStationReference.Load();
                }

                if (!applicationForm.ApplicationProduct.IsLoaded)
                {
                    applicationForm.ApplicationProduct.Load();
                }

                if (!applicationForm.GatheringReference.IsLoaded)
                {
                    applicationForm.GatheringReference.Load();
                }

                foreach (ApplicationProduct applicationProdutct in applicationForm.ApplicationProduct)
                {
                    if (!applicationProdutct.UserReference.IsLoaded)
                    {
                        applicationProdutct.UserReference.Load();
                    }
                    if (!applicationProdutct.User.ServiceStationReference.IsLoaded)
                    {
                        applicationProdutct.User.ServiceStationReference.Load();
                    }
                }
                
                applicationForm.CompleteDateTime = applicationForm.ApplicationProduct.Max(p => p.RepairCompleteDateTime);
            }
            //formslist = formslist.Where(f => f.ApplicationProduct.Where(p => p.RepairCompleteDateTime.HasValue && !p.SendBackTime.HasValue &&
            //    (!(p.IsQuotePrice.HasValue && p.IsQuotePrice.Value) || !(p.IsDecideToRepair.HasValue && p.IsDecideToRepair.Value) || p.ApplicationForm.Gathering != null) &&
            //   (p.UpgradeForm.Count() == 0 || p.UpgradeForm.Where(u => u.Status == "升级-不同意").Count() > 0 || p.UpgradeForm.Where(u => u.SendWay == "客户" || (u.SendWay == "平台" && u.CompleteTime.HasValue)).Count() > 0)).Count() > 0).ToList();
            if (!string.IsNullOrEmpty(keywords))
            {
                formslist = formslist.Where(f => f.ApplicationCode.Contains(keywords) || f.User.ContactPerson.Contains(keywords) ||
                    f.User.CompanyName.Contains(keywords) || f.User.FullName.Contains(keywords) ||
                    f.ApplicationProduct.Where(p => p.User.ContactPerson.Contains(keywords) ||
                        p.User.ServiceStation.Name.Contains(keywords)).Count() > 0).ToList();
            }
            return formslist.OrderByDescending(f=>f.CompleteDateTime).ToList();
        }

        public List<ApplicationForm> GetApplicationFormByStatusAndSendWay(string status, string way)
        {
            List<ApplicationForm> list = GetEntities<ApplicationForm>(p => p.Status == status && p.SendWay == way).ToList();
            foreach (ApplicationForm form in list)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
            }

            return list;
        }


        public RequisitionForm GetRequisitionFormByID(long id)
        {
            return GetEntities<RequisitionForm>(r => r.ID == id).FirstOrDefault();
        }

        public void UpdateRequisitionForm(RequisitionForm form)
        {
            UpdateEntity(form);
        }

        public void SaveFeedback(long applicationID, string maintainQuality, string maintainQualityComment, string maintainPeriod, string maintainPeriodComment,
            string serviceResponse, string serviceResponseComment, string productQuality, string productQualityComment, string productFunction,
            string productFunctionComment, string distributeService, string distributeServiceComment, string cost, string costComment,
            string websiteEvaluate, string websiteEvaluateComment)
        {
            Feedback feedback = new Feedback
            {
                MaintainQuality = maintainQuality,
                MaintainQualityComment = maintainQualityComment,
                MaintainPeriod = maintainPeriod,
                MaintainPeriodComment = maintainPeriodComment,
                ServiceResponse = serviceResponse,
                ServiceResponseComment = serviceResponseComment,
                ProductQuality = productQuality,
                ProductQualityComment = productQualityComment,
                ProductFunction = productFunction,
                ProductFunctionComment = productFunctionComment,
                DistributeService = distributeService,
                DistributeServiceComment = distributeServiceComment,
                Cost = cost,
                CostComment = costComment,
                WebsiteEvaluate = websiteEvaluate,
                WebsiteEvaluateComment = websiteEvaluateComment
            };
            ApplicationForm form = GetApplicationFormByID(applicationID);
            form.Feedback = feedback;
            form.Status = "客户信息反馈";
            //form.ClientReceiveDateTime = DateTime.Now;
            UpdateEntity(form);
            //ApplicationSetStatus(applicationID, "客户信息反馈");
        }

        public void ApplicationSetStatus(long applicationID, string status)
        {
            ApplicationForm form = GetApplicationFormByID(applicationID);
            form.Status = status;
            UpdateApplication(form);
        }

        public void SaveRequistionForm(RequisitionForm requisitionForm)
        {
            InsertEntity(requisitionForm);
        }

        public bool HasApplicationCode(long applicationID)
        {
            bool flug = true;
            ApplicationForm form = GetEntities<ApplicationForm>(a => a.ApplicationID == applicationID).FirstOrDefault();
            if (string.IsNullOrEmpty(form.ApplicationCode))
            {
                flug = false;
            }

            return flug;
        }

        /// <summary>
        /// 2010-03-17: Chen Pu
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="providerID"></param>
        /// <returns></returns>
        public long AddBJXXApplication(long userID, int providerID)
        {
            ApplicationForm applicationForm = new ApplicationForm();
            //rmaApplicationForm.ApplicationID = applicationID;
            applicationForm.ApplicationDateTime = DateTime.Now;
            applicationForm.ApplicationType = "B";
            applicationForm.IsSubmit = false;
            applicationForm.Status = "等待备件单号确认";

            UserService userService = new UserService();
            applicationForm.User = userService.GetUserByID(userID);

            ProviderService providerService = new ProviderService();
            //applicationForm.Provider = providerService.GetProviderByID(providerID);

            InsertEntity(applicationForm);

            return applicationForm.ApplicationID;
        }

        public List<ApplicationForm> GetProductNeedRepairByEngineer(long userID, string keywords)
        {
            List<ApplicationForm> results = new List<ApplicationForm>();
            //IQueryable<ApplicationForm> formList = GetEntities<ApplicationForm>(a => a.ApplicationProduct.Where(p => p.User != null && p.User.UserID == userID && !p.RepairCompleteDateTime.HasValue && (p.Status.Contains("待修") || (p.Status.Contains("报价确认中")&&p.ApplicationForm.Gathering!=null))).Count() > 0
            //    ).OrderByDescending(p => p.ApplicationDateTime);  
            IQueryable<ApplicationForm> formList = GetEntities<ApplicationForm>(a => a.DistributeDateTime.HasValue && a.ApplicationProduct.Where(p => p.User != null && p.User.UserID == userID).Count() > 0 &&
                   !a.CompleteDateTime.HasValue).OrderByDescending(a => a.ApplicationID);
            foreach (ApplicationForm form in formList)
            {
                if (!form.ServiceStationReference.IsLoaded)
                {
                    form.ServiceStationReference.Load();
                }
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
                if (!form.GatheringReference.IsLoaded)
                {
                    form.GatheringReference.Load();
                }
                int productcount = 0;
                foreach (ApplicationProduct applicationProduct in form.ApplicationProduct)
                {
                    if (!applicationProduct.UserReference.IsLoaded)
                    {
                        applicationProduct.UserReference.Load();
                    }
                    
                    if (applicationProduct.User!=null && applicationProduct.User.UserID == userID)
                    {
                        productcount++;
                    }                  
                }

                form.ProductCount = productcount;
                if (string.IsNullOrEmpty(keywords))
                {
                    results.Add(form);
                }
                else if (form.ApplicationCode.Contains(keywords) || form.User.ContactPerson.Contains(keywords) || form.User.CompanyName.Contains(keywords) || form.User.FullName.Contains(keywords) ||
                    form.ServiceStation.Name.Contains(keywords) ||
                    form.ApplicationProduct.Where(pp => pp.User != null && pp.User.ContactPerson.Contains(keywords)).Count() > 0)
                {
                    results.Add(form);
                }
            }

            return results;
        }

        public List<ApplicationForm> GetProductNeed2Repair(string keywords)
        {
            List<ApplicationForm> results = new List<ApplicationForm>();
            //IQueryable<ApplicationForm> formList = GetEntities<ApplicationForm>(a => a.ApplicationProduct.Where(p =>(p.Status.Contains("待修") || (p.Status.Equals("报价确认中") && p.ApplicationForm.Gathering != null)) && !p.RepairCompleteDateTime.HasValue && p.DistributeDateTime.HasValue).Count() > 0).OrderByDescending(p => p.ApplicationDateTime);
            IQueryable<ApplicationForm> formList = GetEntities<ApplicationForm>(a => a.ApplicationProduct.Where(p => p.DistributeDateTime.HasValue).Count() > 0 && !a.CompleteDateTime.HasValue && a.DistributeDateTime.HasValue).OrderByDescending(a => a.ApplicationID);
            
            foreach (ApplicationForm form in formList)
            {
                if (!form.ServiceStationReference.IsLoaded)
                {
                    form.ServiceStationReference.Load();
                }
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
                if (!form.GatheringReference.IsLoaded)
                {
                    form.GatheringReference.Load();
                }
                foreach (ApplicationProduct applicationProduct in form.ApplicationProduct)
                {
                    if (!applicationProduct.UserReference.IsLoaded)
                    {
                        applicationProduct.UserReference.Load();
                    }
                }

                form.ProductCount = form.ApplicationProduct.Where(p => p.DistributeDateTime.HasValue).Count();

                if (string.IsNullOrEmpty(keywords))
                {
                    results.Add(form);
                }
                else if (form.ApplicationCode.Contains(keywords) || form.User.ContactPerson.Contains(keywords) || form.User.CompanyName.Contains(keywords) || form.User.FullName.Contains(keywords) ||
                    form.ServiceStation.Name.Contains(keywords) ||
                    form.ApplicationProduct.Where(pp => pp.User != null && pp.User.ContactPerson.Contains(keywords)).Count() > 0)
                {
                    results.Add(form);
                }
            }

            return results;
        }

        public List<ApplicationForm> GetProductNeed2RepairOfPlatform(int stationID, string keywords)
        {
            //IQueryable<ApplicationForm> formList = GetEntities<ApplicationForm>(a => a.ApplicationProduct.Where(p => p.User != null && !p.RepairCompleteDateTime.HasValue && p.User.ServiceStation.ID == stationID && ((p.Status.Contains("待修") && p.DistributeDateTime.HasValue) || (p.Status.Equals("报价确认中") && p.ApplicationForm.Gathering != null))).Count() > 0 &&
            //    a.Status.Contains("待修") && a.DistributeDateTime.HasValue).OrderBy(p => p.ApplicationCode);
            List<ApplicationForm> results = new List<ApplicationForm>();
            IQueryable<ApplicationForm> formList = GetEntities<ApplicationForm>(a => a.DistributeDateTime.HasValue && a.ApplicationProduct.Where(p => p.DistributeDateTime.HasValue &&
             p.User != null && p.User.ServiceStation.ID == stationID).Count() > 0 && !a.CompleteDateTime.HasValue);
            
            foreach (ApplicationForm form in formList)
            {
                if (!form.ServiceStationReference.IsLoaded)
                {
                    form.ServiceStationReference.Load();
                }
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
                if (!form.GatheringReference.IsLoaded)
                {
                    form.GatheringReference.Load();
                }
                foreach (ApplicationProduct applicationProduct in form.ApplicationProduct)
                {
                    if (!applicationProduct.UserReference.IsLoaded)
                    {
                        applicationProduct.UserReference.Load();
                    }
                }

                form.ProductCount = form.ApplicationProduct.Where(p => p.DistributeDateTime.HasValue && 
                    p.User.ServiceStation.ID == stationID).Count();
                if (string.IsNullOrEmpty(keywords))
                {
                    results.Add(form);
                }
                else if (form.ApplicationCode.Contains(keywords) || form.User.ContactPerson.Contains(keywords) || form.User.CompanyName.Contains(keywords) || form.User.FullName.Contains(keywords) ||
                    form.ServiceStation.Name.Contains(keywords) ||
                    form.ApplicationProduct.Where(pp => pp.User != null && pp.User.ContactPerson.Contains(keywords)).Count() > 0)
                {
                    results.Add(form);
                }
            }

            return results;
        }

        #region private

        private void InsertApplicationToApplicationHistory(ApplicationForm application)
        {
            DeleteEntities<ApplicationProductHistory>(p => p.ApplicationFormHistory.ApplicationID == application.ApplicationID, Guid.Empty);
            DeleteEntities<ApplicationFormHistory>(a => a.ApplicationID == application.ApplicationID, Guid.Empty);

            if (!application.UserReference.IsLoaded)
            {
                application.UserReference.Load();
            }
            //if (!application.ProviderReference.IsLoaded)
            //{
            //    application.ProviderReference.Load();
            //}
            if (!application.ApplicationProduct.IsLoaded)
            {
                application.ApplicationProduct.Load();
            }

            ApplicationFormHistory applicationHistroy = new ApplicationFormHistory()
            {
                ApplicationID = application.ApplicationID,
                RunningNumber = application.RunningNumber,
                User = application.User,
                Status = application.Status,
                CompleteDateTime = application.CompleteDateTime,
                ApplicationDateTime = application.ApplicationDateTime,
                ReceiveDateTime = application.ReceiveDateTime,
                SendDateTime = application.SendDateTime,
                ApplicationType = application.ApplicationType,
                //Provider = application.Provider
            };

            foreach (ApplicationProduct product in application.ApplicationProduct)
            {
                if (!product.ProductTypeReference.IsLoaded)
                {
                    product.ProductTypeReference.Load();
                }
                if (!product.ProblemTypeReference.IsLoaded)
                {
                    product.ProblemTypeReference.Load();
                }

                applicationHistroy.ApplicationProductHistory.Add(ConvertProductToProductHistory(product));

            }

            InsertEntity(applicationHistroy);
        }

        private ApplicationProductHistory ConvertProductToProductHistory(ApplicationProduct product)
        {
            ApplicationProductHistory productHistory = new ApplicationProductHistory
            {
                ApplicationProductID = product.ApplicationProductID,
                ProblemType = product.ProblemType,
                ProductType = product.ProductType,
                ProductCount = product.ProductCount,
                ProductSerialNumber = product.ProductSerialNumber,
                ProductProblemDescription = product.ProductProblemDescription,
                ProductAppearance = product.ProductAppearance,
                ProductPurchaseDateTime = product.ProductPurchaseDateTime,
                RepairAccessory = product.RepairAccessory,
                ProductRepairType = product.ProductRepairType,
                Cost = product.Cost,
                ReasonOfCost = product.ReasonOfCost,
                ReasonOfNotRepair = product.ReasonOfNotRepair,
                Remark = product.Remark,
                Status = product.Status
            };

            return productHistory;
        }

        #endregion


        public bool IsFinishMaintain(long applicationID)
        {
            bool flug = true;
            ApplicationForm form = GetApplicationFormByID(applicationID);
            if (!form.ApplicationProduct.IsLoaded)
            {
                form.ApplicationProduct.Load();
            }
            foreach (ApplicationProduct product in form.ApplicationProduct)
            {
                if (product.Status != "维修完毕待发货")
                {
                    flug = false;
                    break;
                }
            }

            return flug;
        }

        //public bool IsFinishSendProduct(long applicationID)
        //{
        //    bool flug = true;
        //    if (GetEntities<ApplicationProduct>(p => !p.SendBackTime.HasValue).Count() > 0)
        //    {
        //        flug = false;
        //    }

        //    return flug;
        //}

        public void FinishMaintain(long ApplicationID)
        {
            ApplicationForm form = GetApplicationFormByID(ApplicationID);
            if (IsFinishMaintain(ApplicationID))
            {
                form.Status = "维修完毕待发货";
            }

            UpdateApplication(form);
        }

        public List<ApplicationForm> GetApplicationsByKeyWord(string keyword)
        {
            List<ApplicationForm> forms = new List<ApplicationForm>();
            if (!string.IsNullOrEmpty(keyword))
            {
                forms = GetEntities<ApplicationForm>(a => (a.ApplicationCode.Contains(keyword)
            || a.User.FullName.Contains(keyword)
            || a.User.ContactPerson.Contains(keyword)
            || a.User.UserPhone.Contains(keyword)) && a.CompleteDateTime.HasValue).ToList();
            }
            else
            {
                forms = GetEntities<ApplicationForm>(a => a.CompleteDateTime.HasValue).ToList();
            }

            foreach (ApplicationForm form in forms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
            }

            return forms;
        }

        public List<SimpleApplicationModel> GetLatestApplications()
        {
            List<SimpleApplicationModel> applicationModels = new List<SimpleApplicationModel>();
            IQueryable<ApplicationForm> lastestApplications = GetEntities<ApplicationForm>().Where(a => !string.IsNullOrEmpty(a.RunningNumber) && a.IsSubmit.HasValue 
                && a.IsSubmit.Value && !a.ApplicationType.StartsWith("B") && !a.ApplicationType.Equals("0")).OrderByDescending(a => a.ApplicationDateTime).Take(10);
            foreach (ApplicationForm application in lastestApplications)
            {
                SimpleApplicationModel applicationModel = new SimpleApplicationModel();
                applicationModel.ID = application.ApplicationID.ToString();
                if (!application.UserReference.IsLoaded)
                {
                    application.UserReference.Load();
                }
                applicationModel.Customer = application.User.FullName;
                applicationModel.ApplicationDate = application.ApplicationDateTime.HasValue ? application.ApplicationDateTime.Value.ToString() : "";
                if (!application.ApplicationProduct.IsLoaded)
                {
                    application.ApplicationProduct.Load();
                }
                applicationModel.ApplicationCode = application.ApplicationCode;
                applicationModel.Count = application.ApplicationProduct.Count().ToString();
                applicationModels.Add(applicationModel);
            }
            return applicationModels;
        }

        public List<SimpleApplicationModel> GetLatestBJXXApplications()
        {
            List<SimpleApplicationModel> applicationModels = new List<SimpleApplicationModel>();
            IQueryable<ApplicationForm> lastestApplications = GetEntities<ApplicationForm>().Where(a => !string.IsNullOrEmpty(a.RunningNumber) && a.IsSubmit.HasValue && a.IsSubmit.Value && 
                (a.ApplicationType.StartsWith("B"))).OrderByDescending(a => a.ApplicationDateTime).Take(10);
            foreach (ApplicationForm application in lastestApplications)
            {
                SimpleApplicationModel applicationModel = new SimpleApplicationModel();
                applicationModel.ID = application.ApplicationID.ToString();
                if (!application.UserReference.IsLoaded)
                {
                    application.UserReference.Load();
                }
                applicationModel.Customer = application.User.FullName;
                applicationModel.ApplicationDate = application.ApplicationDateTime.HasValue ? application.ApplicationDateTime.Value.ToString() : "";
                if (!application.ApplicationProduct.IsLoaded)
                {
                    application.ApplicationProduct.Load();
                }
                applicationModel.ApplicationCode = application.ApplicationCode;
                applicationModel.Count = application.ApplicationProduct.Count().ToString();
                applicationModels.Add(applicationModel);
            }
            return applicationModels;
        }

        public List<ApplicationFormHistory> GetAllBJXXOriginalApplication()
        {
            IQueryable<ApplicationFormHistory> formlist = GetEntities<ApplicationFormHistory>(a => a.ApplicationType.StartsWith("B")).OrderByDescending(p => p.ApplicationID);
            foreach (ApplicationFormHistory form in formlist)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProductHistory.IsLoaded)
                {
                    form.ApplicationProductHistory.Load();
                }
            }

            return formlist.ToList();
        }

        public List<ApplicationForm> GetBJXXApplicationByStatus(string status)
        {
            IQueryable<ApplicationForm> formlist = GetEntities<ApplicationForm>(a => a.ApplicationType == "B" && a.Status == status).OrderByDescending(p => p.ApplicationID);
            foreach (ApplicationForm form in formlist)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
            }

            return formlist.ToList();
        }

        //public List<ApplicationOverDueModel> GetApplicationByRoleAndUserID(int roleNumber, long userID)
        //{
        //    List<ApplicationOverDueModel> applicationModelList = new List<ApplicationOverDueModel>();
        //    int repairDays = 0;
        //    if (roleNumber == (int)RoleType.CustomerManager || roleNumber == (int)RoleType.CustomerMonitor || roleNumber == (int)RoleType.Manager || roleNumber == (int)RoleType.Administrator)
        //    {
        //        IQueryable<ApplicationForm> applicationsOverDue = GetEntities<ApplicationForm>(a => a.RMANOGenerateDateTime.HasValue && a.ClientReceiveDateTime.HasValue == false && a.IsSubmit == true);
        //        foreach (ApplicationForm form in applicationsOverDue)
        //        {
        //            repairDays = GetRepairDays(form.ApplicationDateTime.Value);
        //            if (repairDays >= 2)
        //            {
        //                if (!form.UserReference.IsLoaded)
        //                {
        //                    form.UserReference.Load();
        //                }
        //                applicationModelList.Add(new ApplicationOverDueModel
        //                {
        //                    ApplicationCode = form.ApplicationCode,
        //                    Customer = form.User.FullName,
        //                    DistributeDate = form.DistributeDateTime.HasValue ? form.DistributeDateTime.Value.ToString("yyyy-MM-dd") : "",
        //                    ID = form.ApplicationID,
        //                    PhoneNumber = form.User.UserPhone,
        //                    repairDay = repairDays,
        //                    Status = form.Status,
        //                });
        //            }
        //        }
        //    }
        //    else if (roleNumber == (int)RoleType.Engineer)
        //    {
        //        IQueryable<ApplicationForm> applicationsOverDue = GetEntities<ApplicationForm>(a =>a.RMANOGenerateDateTime.HasValue && a.ClientReceiveDateTime.HasValue == false && a.IsSubmit == true && a.ApplicationProduct.Where(p => p.User.UserID == userID).Count() > 0);
        //        foreach (ApplicationForm form in applicationsOverDue)
        //        {
        //            repairDays = GetRepairDays(form.ApplicationDateTime.Value);
        //            if (repairDays >= 2)
        //            {
        //                if (!form.UserReference.IsLoaded)
        //                {
        //                    form.UserReference.Load();
        //                }
        //                applicationModelList.Add(new ApplicationOverDueModel
        //                {
        //                    ApplicationCode = form.ApplicationCode,
        //                    Customer = form.User.FullName,
        //                    DistributeDate = form.DistributeDateTime.Value.ToString("yyyy-MM-dd"),
        //                    ID = form.ApplicationID,
        //                    PhoneNumber = form.User.UserPhone,
        //                    repairDay = repairDays,
        //                    Status = form.Status
        //                });
        //            }
        //        }
        //    }

        //    return applicationModelList;
        //}

        private int GetRepairDays(DateTime applyDateTime)
        {
            DateTime endTime = DateTime.Now.Date;
            int days = 0;
            for (DateTime startTime = applyDateTime.Date; startTime < endTime; startTime = startTime.AddDays(1))
            {
                if (startTime.DayOfWeek != DayOfWeek.Saturday && startTime.DayOfWeek != DayOfWeek.Sunday)
                {
                    days++;
                }
            }

            return days;
        }

        public IQueryable<ApplicationForm> GetApplicationsByYear(int year)
        {
            return GetEntities<ApplicationForm>(a => a.ApplicationDateTime.Value.Year == year).OrderByDescending(a => a.ApplicationDateTime.Value);
        }

        internal List<ApplicationForm> GetApplicationQuatationOverdue()
        {
            IQueryable<ApplicationForm> forms = GetEntities<ApplicationForm>(a => a.QuatationDatetime.HasValue);
            List<ApplicationForm> formList = new List<ApplicationForm>();
            foreach (ApplicationForm form in forms)
            {
                //(DateTime.Now - a.QuatationDatetime.Value).Days >= 3 && ((DateTime.Now - a.QuatationDatetime.Value).Days - 3) % 2 == 0
                if (DateTimeService.CalculateDateTimeSpan(form.QuatationDatetime.Value, DateTime.Now) > 5 &&
                    (DateTimeService.CalculateDateTimeSpan(form.QuatationDatetime.Value, DateTime.Now) - 5) % 2 == 0)
                {
                    formList.Add(form);
                }
            }
            return formList;
        }

        public List<ConfirmQuatationModel> GetApplicationFormsNeedConfirmQuatation(string keyword)
        {
            List<ConfirmQuatationModel> models = new List<ConfirmQuatationModel>();     
            IQueryable<ApplicationForm> forms = GetEntities<ApplicationForm>().Where(a => a.QuatationDatetime.HasValue && !a.ConfirmQuatationCompleteDate.HasValue);
            if (!string.IsNullOrEmpty(keyword))
            {
                forms = forms.Where(a => a.ApplicationCode.Contains(keyword) ||
                    a.User.FullName.Contains(keyword) ||
                    a.User.UserMobilePhone.Contains(keyword) ||
                    a.User.CompanyName.Contains(keyword) ||
                    a.User.ContactPerson.Contains(keyword) ||
                    a.ApplicationProduct.Where(p => p.ProductSerialNumber.Contains(keyword)).Count() > 0 ||
                    a.ApplicationProduct.Where(p => p.ProblemType.Name.Contains(keyword)).Count() > 0 ||
                    a.ApplicationProduct.Where(p => p.ProductType.ProductTypeName != null && p.ProductType.ProductTypeName.ToLower().Contains(keyword.ToLower())).Count() > 0);
            }
            foreach (ApplicationForm form in forms)
            {
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
                if (!form.ApplicationProduct.IsLoaded)
                {
                    form.ApplicationProduct.Load();
                }
                foreach (ApplicationProduct product in form.ApplicationProduct)
                {
                    if (!product.QuatationForm.IsLoaded)
                    {
                        product.QuatationForm.Load();
                    }
                }

                ConfirmQuatationModel model = new ConfirmQuatationModel()
                {
                    ApplicationID = form.ApplicationID,
                    ApplicationCode = form.ApplicationCode,
                    ClientName = form.User.FullName,
                    ClientPhoneNumber = form.User.UserPhone,
                    Days = (DateTime.Now - form.QuatationDatetime.Value).Days,
                    QuataionDate = form.QuatationDatetime.Value.ToString("yyyy-MM-dd HH:mm"),
                    ReceiveDate = form.ReceiveDateTime.Value.ToString("yyyy-MM-dd HH:mm")
                };

                models.Add(model);
            }
            return models.OrderByDescending(q=>q.QuataionDate).ToList();
        }

        public long GetFormIDByProductID(long productID)
        {
            ApplicationProduct product = GetEntities<ApplicationProduct>().Where(p => p.ApplicationProductID == productID).FirstOrDefault();
            if (!product.ApplicationFormReference.IsLoaded)
            {
                product.ApplicationFormReference.Load();
            }
            return product.ApplicationForm.ApplicationID;
        }

        public void ClientReceiveAllProducts(long applicationID)
        {
            ApplicationForm form = GetApplicationFormByID(applicationID);
            if (!form.ApplicationProduct.IsLoaded)
            {
                form.ApplicationProduct.Load();
            }
            if (form.ApplicationProduct.Where(p => !p.ClientReceiveDateTime.HasValue).Count() == 0)
            {
                form.Status = "客户已收货确认";
                UpdateApplication(form);
            }
        }

        public IQueryable<ApplicationForm> GetKPApplication(string keyword)
        {
            IQueryable<ApplicationForm> forms = GetEntities<ApplicationForm>(a => a.KPDateTime.HasValue).OrderByDescending(a=>a.KPDateTime.Value);
            if (!string.IsNullOrEmpty(keyword))
            {
                forms = forms.Where(f => f.ApplicationCode.Contains(keyword) || f.User.FullName.Contains(keyword));
            }

            foreach (ApplicationForm form in forms)
            {
                if (!form.GatheringReference.IsLoaded)
                {
                    form.GatheringReference.Load();
                }
                if (!form.UserReference.IsLoaded)
                {
                    form.UserReference.Load();
                }
            }

            return forms;
        }
    }
}
